
//for debugging purposes ... var nya dibuat saja, agar bisa dioprek oprek di console
var headID;
var newScript;

//fungsi untuk mencheck apakah variable kel1 kel2 kel3 dst ada di localStorage
function check_kel(id){

	if(typeof(Storage)!=="undefined")
	{
		//browser dukung localStorage

		console.log('check_kel ' + id);
		if(localStorage.getItem('kel'+id)==null){
			console.log('kel'+id +' tidak terdapat di localStorage');
			console.log('mencoba menambahkan data dari server');
			
			headID = document.getElementsByTagName("head")[0];         
			newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.src = '/json/shape/'+id + '';
			//jika selesai load file javascriptnya, panggil fungsi simpan_kel			
			newScript.onload=simpan_kel(id);
			headID.appendChild(newScript);
		}else{
			console.log('data kelurahan sudah terdapat');
			console.log('kel'+id+'='+localStorage.getItem('kel'+id));
			window['kel'+id]= JSON.parse(localStorage.getItem('kel'+id));
		}		
		
	}
	else
	{
		//browser tidak dukung localStorage
	
		headID = document.getElementsByTagName("head")[0];         
		newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src = '/json/shape/'+id + '';//load our shape
		//newScript.onload=simpan_kel(id);			
		headID.appendChild(newScript);		
	}


}

var tried=0;
//walaupun sudah diload file scriptnya, belum berati filenya sudah dieksekusi, jadi kita harus sabar
function simpan_kel(id){
	console.log('simpan_kel('+id+')');
	if (undefined===window['kel'+id]) {
		console.log('variable kel'+id+' belum terdefinisikan. Tried:'+tried);
		//variable kel+id belum terdefinisikan
		//set timeout agar dicoba lagi 1s
		tried++;
		if(tried<5)
		setTimeout(simpan_kel(id),5000);//check again for next 5 second 4 times
	}else{
		console.log('saving kel'+id+' into localStorage');
		localStorage.setItem('kel'+id,JSON.stringify(window['kel'+id]));
	}
	//localStorage.setItem('kel'+id,JSON.stringify(kel1));
	//yang di atas tidak mau!!!, 
	//mungkin kel1 belum terdefinisikan walaupun sudah diload file javascriptnya???
	
	//document.getElementById('kel'+id).innerHTML='Sukses Mendownload data untuk Kelurahan '+id+'.<br/><a href="javascript:local_kel('+id+',kel'+id+')">Klik untuk menyimpan</a>.';
}

/*
function local_kel(id,kel){
	localStorage.setItem('kel'+id,JSON.stringify(kel));
	console.log(localStorage.getItem('kel'+id));
}
*/
